import json
from datetime import datetime
from rest_framework.generics import DestroyAPIView
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from django.views.generic import View

# Create your views here.
from BookTest.serializers import BookInfoSerializer
from .models import BookInfo, HeroInfo


class IndexView(View):
    def get(self, request):
        context = {
            'city': 'beijing',
            'alist': [1, 2, 3],
            'adict': {
                'name': 'python'
            }
        }
        return render(request, 'index.html', context)


# REST　API


class BooksView(View):
    # GET    /books/    获取全部图书
    def get(self, request):
        print("BooksView视图函数被调用")
        books = BookInfo.objects.all()
        # print(books)
        book_list = []
        for book in books:
            book_list.append({
                "id": book.id,
                "btitle": book.btitle,
                "bpub_date": book.bpub_date.strftime('%Y-%m-%d'),
                "bread": book.bread,
                "bcomment": book.bcomment,
            })
        return JsonResponse(book_list, safe=False)

    # POST    /books/    创建图书
    def post(self, request):
        json_bytes = request.body
        json_str = json_bytes.decode()
        book_dict = json.loads(json_str)
        book = BookInfo.objects.create(
            btitle=book_dict.get("btitle"),
            bpub_date=datetime.strptime(book_dict.get('bpub_date'), '%Y-%m-%d').date()
        )
        return JsonResponse({
            'id': book.id,
            'btitle': book.btitle,
            'bpub_date': book.bpub_date,
            'bread': book.bread,
            'bcomment': book.bcomment,
        }, status=201)


# GET    /book/<pk>/    获取单个图书
# PUT    /book/<pk>/    更新图书信息
# DELETE    /book/<pk>/    删除图书

from rest_framework.viewsets import ModelViewSet


class BooksInfoViewSet(ModelViewSet):
    queryset = BookInfo.objects.all()
    serializer_class = BookInfoSerializer
